package io.bluerain.io;

import io.bluerain.core.Obj;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class IO {

    public static File readOrCreateFile(String filename) {
        File file = new File(filename);
        return file;
    }

    public static String readText(String filename) throws IOException {
        File file = readOrCreateFile(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream(file)));
        StringBuffer sb = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        if (br != null)
            br.close();
        return sb.toString();
    }

    public static List<String> readLines(String filename, OpeContent... oc) throws IOException {
        File file = readOrCreateFile(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream(file)));
        List<String> lines = new ArrayList<>();
        String line = null;
        OpeContent opeContent = null;
        if (Obj.notNullOrEmpty(oc)) {
            opeContent = oc[0];
            opeContent.before();
            while ((line = br.readLine()) != null) {
                try {
                    opeContent.readLine(line);
                } catch (Exception e) {
                    e.printStackTrace();
                    if (br != null)
                        br.close();
                    return lines;
                }
                lines.add(line);
            }
            opeContent.result();
        } else {
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        }
        if (br != null)
            br.close();
        return lines;
    }

}
